package com.catazy.album.presentation.screen.albumdetail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Star
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ElevatedSuggestionChip
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.fragment.navArgs
import com.catazy.album.R
import com.catazy.album.domain.model.Tag
import com.catazy.album.domain.model.Track
import com.catazy.album.presentation.screen.albumdetail.AlbumDetailViewModel.UiState
import com.catazy.album.presentation.screen.albumdetail.AlbumDetailViewModel.UiState.Content
import com.catazy.album.presentation.screen.albumdetail.AlbumDetailViewModel.UiState.Error
import com.catazy.album.presentation.screen.albumdetail.AlbumDetailViewModel.UiState.Loading
import com.catazy.album.presentation.util.TimeUtil
import com.catazy.base.common.res.Dimen
import com.catazy.base.presentation.activity.BaseFragment
import com.catazy.base.presentation.compose.composable.DataNotFoundAnim
import com.catazy.base.presentation.compose.composable.PlaceholderImage
import com.catazy.base.presentation.compose.composable.ProgressIndicator
import com.catazy.base.presentation.compose.composable.TextTitleLarge
import com.catazy.base.presentation.compose.composable.TextTitleMedium
import kotlinx.coroutines.flow.StateFlow
import org.koin.androidx.navigation.koinNavGraphViewModel

/**
 * 作者: Tao
 * 日期: 2024/12/24
 * 时间: 09:54
 * 描述: 专辑详情片段类，用于展示专辑的详细信息
 */
internal class AlbumDetailFragment : BaseFragment() {

    // 使用NavArgs插件获取导航参数
    private val args: AlbumDetailFragmentArgs by navArgs()

    // 通过Koin获取ViewModel实例，用于处理业务逻辑
    private val model: AlbumDetailViewModel by koinNavGraphViewModel(R.id.albumNavGraph)

    /**
     * 创建视图方法，用于设置片段的布局和初始化逻辑
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 调用ViewModel的onEnter方法，处理进入片段时的逻辑
        model.onEnter(args)

        // 使用ComposeView创建视图，并设置内容
        return ComposeView(requireContext()).apply {
            setContent {
                AlbumDetailScreen(uiStateFlow = model.uiStateFlow)
            }
        }
    }
}

/**
 * 专辑详情屏幕的可组合函数，用于展示专辑详情的UI
 */
@Composable
private fun AlbumDetailScreen(uiStateFlow: StateFlow<UiState>) {
    // 收集UI状态并根据状态展示不同的UI
    // collectAsStateWithLifecycle 是 Jetpack Compose 提供的一个扩展函数，它确保状态的收集与生命周期关联，
    // 从而在生命周期处于非活跃状态时暂停收集，并在生命周期恢复时重新开始收集
    val uiState: UiState by uiStateFlow.collectAsStateWithLifecycle()

    uiState.let {
        when (it) {
            Error -> DataNotFoundAnim() // 展示数据加载错误的动画
            Loading -> ProgressIndicator() // 展示数据加载中的进度指示器
            is Content -> PhotoDetails(it) // 展示具体内容
        }
    }
}

/**
 * 展示专辑详情内容的可组合函数
 */
@Composable
private fun PhotoDetails(content: Content) {
    Column(
        modifier = Modifier
            .padding(Dimen.screenContentPadding)
            // 为 Column 添加垂直滚动功能
            // rememberScrollState() 是 Jetpack Compose 提供的一个函数，用于创建和管理滚动状态
            .verticalScroll(rememberScrollState())
    ) {
        // 使用卡片展示专辑封面、名称和艺术家信息
        // ElevatedCard 是 Jetpack Compose 提供的一个带有阴影效果的卡片组件
        ElevatedCard(
            modifier = Modifier
                .padding(Dimen.spaceM)
                // 宽度自适应
                .wrapContentSize()
                // 设置卡片的固定大小为 320dp
                .size(320.dp)
                // 将卡片水平居中
                .align(Alignment.CenterHorizontally)
        ) {
            PlaceholderImage(
                url = content.coverImageUrl,
                contentDescription = stringResource(id = R.string.album_cover_content_description),
                modifier = Modifier.fillMaxWidth()
            )
        }
        // 添加一些间距
        Spacer(modifier = Modifier.height(Dimen.spaceL))
        TextTitleLarge(text = content.albumName)
        TextTitleMedium(text = content.artistName)
        Spacer(modifier = Modifier.height(Dimen.spaceL))

        // 展示专辑标签
        if (content.tags.isNotEmpty()) {
            Tags(content.tags)
            Spacer(modifier = Modifier.height(Dimen.spaceL))
        }

        // 展示专辑曲目
        if (content.tracks.isNotEmpty()) {
            TextTitleMedium(text = stringResource(id = R.string.tracks))
            Spacer(modifier = Modifier.height(Dimen.spaceL))
            Tracks(content.tracks)
        }
    }
}

/**
 * 展示专辑标签的可组合函数
 */
@Composable
@OptIn(ExperimentalLayoutApi::class)
private fun Tags(tags: List<Tag>) {
    // FlowRow 是 Jetpack Compose 提供的一个布局组件，用于在水平方向上排列子组件，并在需要时换行
    FlowRow {
        tags.forEach {
            // ElevatedSuggestionChip 是一个带有阴影效果的建议芯片组件，用于展示标签或建议项
            ElevatedSuggestionChip(
                label = { Text(text = it.name) },
                onClick = {}
            )
        }
    }
}

/**
 * 展示专辑曲目的可组合函数
 */
@Composable
internal fun Tracks(tracks: List<Track>) {
    tracks.forEach {
        Track(it)
    }
}

/**
 * 展示单个曲目信息的可组合函数
 */
@Composable
internal fun Track(track: Track) {
    Row {
        Icon(Icons.Outlined.Star, null)
        Spacer(modifier = Modifier.width(Dimen.spaceS))

        var text = track.name

        // 如果曲目有时长信息，则添加到展示文本中
        track.duration?.let {
            text += " ${TimeUtil.formatTime(track.duration)}"
        }

        Text(text = text)
    }
}
